package cn.witsky.rtp2ws.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.witsky.rtp2ws.Server;

public class FFMPEG_Util {
	private static Logger logger = LoggerFactory.getLogger(FFMPEG_Util.class);
	static String firstCommandStr=Server.ffmpegBinPath+" -i "+Server.downLoadDir+"/%s  -map_channel 0.0.0 "+Server.downLoadDir+"/%s  -map_channel 0.0.1 "+Server.downLoadDir+"/%s";
	static String secondCommandStr=Server.ffmpegBinPath+" -i "+Server.downLoadDir+"/%s -f s16le -ar 8000 -ac 1 -acodec pcm_s16le "+Server.downLoadDir+"/%s";
	static String thirdCommandStr=Server.ffmpegBinPath+" -i "+Server.downLoadDir+"/%s -f s16le -ar 8000 -ac 1 -acodec pcm_s16le "+Server.downLoadDir+"/%s";
	
	public static boolean exec(String callId,String suffix) {
		boolean isSuc=false;
		int exitValue=-1;
		Process process = null;
		try {
			String firstCommand=String.format(firstCommandStr, callId+"."+suffix,callId+"-caller."+suffix,callId+"-called."+suffix);
			process = Runtime.getRuntime().exec(firstCommand);
			exitValue = process.waitFor();
			if (exitValue == 0) {
				logger.info("exec firstCommand:{} success",firstCommand);
				String secondCommand=String.format(secondCommandStr, callId+"-caller."+suffix,callId+"-caller.pcm");
				process=Runtime.getRuntime().exec(secondCommand);
				exitValue = process.waitFor();
				if(exitValue==0) {
					logger.info("exec secondCommand:{} success",secondCommand);
					String thirdCommand=String.format(thirdCommandStr,callId+"-called."+suffix,callId+"-called.pcm");
					process=Runtime.getRuntime().exec(thirdCommand);
					exitValue = process.waitFor();
					if(exitValue!=0) {
						logger.warn("exec thirdCommand:{} error",thirdCommand);
					}else {
						logger.info("exec thirdCommand:{} success",thirdCommand);
						isSuc=true;
					}
				}else {
					logger.warn("exec secondCommand:{} error",secondCommand);
				}
			}else {
				logger.warn("exec firstCommand:{} error",firstCommand);
			}
		} catch (Exception ex) {
			logger.info("调用 ffmpeg出现异常:",ex);
		}
		return isSuc;
	}
}
